<script setup>
import { reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { login as adminLogin } from '@/api/user';
import { useStore } from '@/store';

const router = useRouter();
const store = useStore();
const loginForm = reactive({
    username: '',
    password: '',
    role:"admin"
});

// 移除错误消息的onMounted

const login = async () => {
    try {
        // 调用管理员登录API
        const res = await adminLogin(loginForm);
        console.log(res);
        
        if (res.data && res.code === 200) {
            // 登录成功，保存token
            store.setToken(res.data);
            ElMessage({
                message: res.msg || '登录成功',
                type: 'success'
            });
            // 跳转到首页
            router.push({ path: '/' });
        } else {
            // 登录失败
            ElMessage({
                message: res.msg || '登录失败，请检查用户名和密码',
                type: 'error'
            });
        }
    } catch (error) {
        console.error('登录错误:', error);
        ElMessage({
            message: '登录失败，请稍后再试',
            type: 'error'
        });
    }
}
</script>


<template>
    <div class="body-login">
        <el-form :model="loginForm" class="login-container" @keyup.enter="login">
            <h1>欢迎登陆</h1>
            <el-form-item>
                <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="login">登陆</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
</script>

<style scoped lang="less">
.body-login {
    width: 100%;
    height: 100%;
    background-image: url("../assets/images/background.png");
    background-size: 100%;
    overflow: hidden;
}

.login-container {
    width: 400px;
    background-color: #fff;
    border: 1px solid #eaeaea;
    border-radius: 15px;
    padding: 35px 35px 15px 35px;
    box-shadow: 0 0 25px #cacaca;
    margin: 250px auto;

    h1 {
        text-align: center;
        margin-bottom: 20px;
        color: #505450;
    }

    :deep(.el-form-item__content) {
        justify-content: center;
    }
}
</style>